<?php

class CommentController extends BaseController
{
    protected $tableName = "comment";
    protected $pk = "comment_id";

    // 重写新建评论方法
    public function post($obj)
    {
        $user_id = $obj['user_id'];
        $answer_id = $obj['answer_id'];
        $comment_content = $obj['comment_content'];
        $sql = "INSERT INTO `comment` VALUES(0,$user_id,$answer_id,'$comment_content',CURRENT_TIME)";
        $result = $this->conn->query($sql);
        if ($this->judge($result)) {
            $data = $this->getNewRecord($obj);
            return ReturnHelper::success($data, "评论新增成功");
        }
        else {
            return ReturnHelper::failed([], "评论新增失败");
        }
    }

    // GET 获取某评论下的对话
    public function getReplies($comment_id) {
        // 判断是否登录，如果已登录还需返回该评论是否是由当前用户发表的信息
        $loginInfo = LoginController::getLoginInfo();
        $sqlPart = "FALSE 'byLoginUser'";
        if ($loginInfo['isLogin']) {
            $user_id = $loginInfo['user_id'];
            $sqlPart = "IF(userfrom.user_id = $user_id, true, false) 'byLoginUser'";
        }
        $sql = "SELECT '用户信息', userfrom.user_id 'userfrom_userId', userfrom.nickname 'userfrom_nickname', userfrom.avatar_url 'userfrom_avatar',
                                    userto.user_id 'userto_userId', userto.nickname 'userto_nickname', userto.avatar_url 'userto_avatar', $sqlPart,
                        '对话信息', c.cm_reply_id, c.cm_reply_content, c.create_time 
                FROM comment_reply c, `user` userfrom, `user` userto
                WHERE c.user_from = userfrom.user_id AND c.user_to = userto.user_id
                        AND comment_id = $comment_id
                ORDER BY c.create_time";
        $result = $this->conn->query($sql);
        $data = $this->getArrayDataFromResult($result);
        if (empty($data)) {
            return ReturnHelper::failed([], "评论`$comment_id`下的对话为空");
        }
        else {
            return ReturnHelper::success($data, "评论`$comment_id`下的对话请求成功");
        }
    }
}